﻿using System;
using System.Collections.Generic;
using Orchard.ContentManagement;
using Orchard.ContentManagement.MetaData;
using Orchard.ContentManagement.MetaData.Builders;
using Orchard.ContentManagement.MetaData.Models;
using Orchard.ContentManagement.ViewModels;

namespace Contrib.DecoratorField.Settings {
    public class DecoratorFieldEditorEvents : ContentDefinitionEditorEventsBase {

        public override IEnumerable<TemplateViewModel>
          PartFieldEditor(ContentPartFieldDefinition definition) {
            if (definition.FieldDefinition.Name == "DecoratorField") {
                var model = definition.Settings.GetModel<DecoratorFieldSettings>();
                yield return DefinitionTemplate(model);
            }
        }

        public override IEnumerable<TemplateViewModel> PartFieldEditorUpdate(
          ContentPartFieldDefinitionBuilder builder, IUpdateModel updateModel) {
            var model = new DecoratorFieldSettings();
            if (builder.FieldType != "DecoratorField") {
              yield break;
            }

            if (updateModel.TryUpdateModel(model, "DecoratorFieldSettings", null, null)) {
                builder.WithSetting("DecoratorFieldSettings.Mode",
                                    model.Mode.ToString());
                builder.WithSetting("DecoratorFieldSettings.HtmlTag",
                                    model.HtmlTag.ToString());
                builder.WithSetting("DecoratorFieldSettings.HasAttributes",
                                    model.HasAttributes.ToString());
                builder.WithSetting("DecoratorFieldSettings.Attributes",
                                    string.IsNullOrEmpty(model.Attributes) ? string.Empty : model.Attributes.ToString());
                builder.WithSetting("DecoratorFieldSettings.CssClass",
                                    string.IsNullOrEmpty(model.CssClass) ? string.Empty : model.CssClass);
                builder.WithSetting("DecoratorFieldSettings.HasContent",
                                    model.HasContent.ToString());
                builder.WithSetting("DecoratorFieldSettings.TagContent",
                    string.IsNullOrEmpty(model.TagContent) ? string.Empty:model.TagContent.ToString());
              }

            yield return DefinitionTemplate(model);
        }
    }
}